package com.example.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.enums.RoleEnum;
import com.example.entity.Employee;
import com.example.entity.AttendanceRecords;
import com.example.entity.Leaves;
import com.example.mapper.AttendanceRecordsMapper;
import com.example.service.AttendanceRecordsService;
import com.example.service.EmployeeService;
import com.example.service.LeavesService;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * @Description TODO
 * @Author dingchunlin
 * @Date 2023/12/31 11:37
 * @Version 1.0.0
 */
@Slf4j
@Service
public class AttendanceRecordsServiceImpl extends ServiceImpl<AttendanceRecordsMapper, AttendanceRecords> implements AttendanceRecordsService {

    @Autowired
    private AttendanceRecordsMapper attendanceRecordsMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private LeavesService leavesService;

    /**
     * 新增
     *
     * @param attendanceRecords
     */
    @Override
    public void add(AttendanceRecords attendanceRecords) {
        attendanceRecordsMapper.insert(attendanceRecords);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        attendanceRecordsMapper.deleteById(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            attendanceRecordsMapper.deleteById(id);
        }
    }

    /**
     * 修改
     *
     * @param attendanceRecords
     */
    @Override
    public void updateAttendanceRecords(AttendanceRecords attendanceRecords) {
        attendanceRecordsMapper.updateById(attendanceRecords);
    }

    /**
     * 根据ID查询
     *
     * @param id
     */
    @Override
    public AttendanceRecords selectById(Integer id) {
        return attendanceRecordsMapper.selectById(id);
    }

    /**
     * 查询所有
     *
     * @param attendanceRecords
     */
    @Override
    public List<AttendanceRecords> selectAll(AttendanceRecords attendanceRecords) {
        LambdaQueryWrapper<AttendanceRecords> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<AttendanceRecords> recordsList = attendanceRecordsMapper.selectList(lambdaQueryWrapper);
        recordsList.forEach( item ->{
            Integer employeeId = item.getEmployeeId();
            Employee employee = employeeService.selectById(employeeId);
            item.setEmployeeName(employee.getName());
            item.setDepartmentName(employee.getDepartmentName());
            //如果迟到的时间非空就返回是
            if (ObjectUtil.isNotEmpty(item.getLateTime())){
                item.setIsLate("是");
            }else {
                item.setIsLate("否");
            }
            if (ObjectUtil.isNotEmpty(item.getEarlyTime())){
                item.setIsEarly("是");
            }else {
                item.setIsEarly("否");
            }
        });
        return recordsList;
    }

    /**
     * 分页查询
     *
     * @param attendanceRecords
     * @param pageNum
     * @param pageSize
     */
    @Override
    public PageInfo<AttendanceRecords> selectPage(AttendanceRecords attendanceRecords, Integer pageNum, Integer pageSize,Boolean isQueryAll) {
        Employee user = TokenUtils.getCurrentUser();
        LambdaQueryWrapper<AttendanceRecords> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(AttendanceRecords::getId);
        if (isQueryAll){
            //部门主管只能查看自己部门下员工的考勤信息
            if (user.getRole().equals(RoleEnum.DEPARTMENT_MANAGER.name())){
                Employee employee = employeeService.selectById(user.getId());
                Integer departmentId = employee.getDepartmentId();
                List<Integer> list = employeeService.selectIdByDepartmentId(departmentId);
                lambdaQueryWrapper.in(AttendanceRecords::getEmployeeId, list);
            }
        }else {
            lambdaQueryWrapper.eq(AttendanceRecords::getEmployeeId, user.getId());
        }

        //根据用户姓名进行条件查询
        if(ObjectUtil.isNotEmpty(attendanceRecords.getEmployeeName())){
            //进行查询
            Employee employee = employeeService.selectByName(attendanceRecords.getEmployeeName());
            //如果没有该用户直接返回null
            if (employee == null){
                return null;
            }else {
                //查询考勤id为查询用户名的id
                lambdaQueryWrapper.eq(AttendanceRecords::getEmployeeId, employee.getId());
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        List<AttendanceRecords> recordsList = attendanceRecordsMapper.selectList(lambdaQueryWrapper);
        recordsList.forEach( item ->{
            Integer employeeId = item.getEmployeeId();
            Employee employee = employeeService.selectById(employeeId);
            item.setEmployeeName(employee.getName());
            item.setDepartmentName(employee.getDepartmentName());
            //如果迟到的时间非空就返回是
            if (ObjectUtil.isNotEmpty(item.getLateTime())){
                item.setIsLate("是");
            }else {
                item.setIsLate("否");
            }
            if (ObjectUtil.isNotEmpty(item.getEarlyTime())){
                item.setIsEarly("是");
            }else {
                item.setIsEarly("否");
            }
        });
        return PageInfo.of(recordsList);
    }

    /**
     * 这个是每周一到周五两点执行代码
     */
    @Scheduled(cron = "0 0 2 * * 1-5")
    @Override
    public void doSomething() {
        //首先查询出所有的员工
        List<Employee> employees = employeeService.selectAll(new Employee());
        employees.forEach( item ->{
            Integer id = item.getId();
            //创建一个考勤实体
            AttendanceRecords attendanceRecords = new AttendanceRecords();
            //设置参数
            attendanceRecords.setEmployeeId(id);
            attendanceRecords.setDate(new Date());
            //查询当前用户是否在请假中
            Leaves leaves = leavesService.queryIsLeaves(id, LocalDateTime.now());
            if (ObjectUtil.isNotEmpty(leaves)){
                attendanceRecords.setLeaveStatus(leaves.getLeaveType());
            }else {
                attendanceRecords.setLeaveStatus("正常");
            }
            //进行保存
            add(attendanceRecords);
        });
    }

    @Override
    public void clockIn(Integer id) {
        AttendanceRecords attendanceRecords = selectById(id);
        //将打卡时间和固定上班打卡时间进行判断
        Date date = attendanceRecords.getDate();
        //这里表示将今天时间转成时间戳并加9小时
        long time = date.getTime();
        time = time +32400000;
//        long time = 1703984400000L;
        //将当前时间进行比较
        LocalDateTime now = LocalDateTime.now();
        //设置打卡时间
        attendanceRecords.setStartTime(now);
        // 将 LocalDateTime 转换为时间戳（单位：毫秒）
        long timestampInMillis = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
//        long timestampInMillis = 1703989240000L;
        //如果为true就表示迟到了
        if (timestampInMillis > time){
            long reduce = timestampInMillis - time;
            //小时
            double hr = Math.floor(reduce / 3600000 % 24);
            reduce = reduce - (long)(hr * 3600000 );
            // 分钟
            double min = Math.floor(reduce / 60000 % 60);
            String lateTime = new String();
            lateTime = hr + "时" + min + "分";
            attendanceRecords.setLateTime(lateTime);
        }
        //执行修改
        updateById(attendanceRecords);
    }

    /**
     * 下班打卡
     * @param id
     */
    @Override
    public void clockOut(Integer id) {
        AttendanceRecords attendanceRecords = selectById(id);
        //将打卡时间和固定上班打卡时间进行判断
        Date date = attendanceRecords.getDate();
        //这里表示将今天时间转成时间戳并加9小时
        long time = date.getTime();
        time = time + (18 * 3600 * 1000);
//        long time = 1704016800000L;
        //将当前时间进行比较
        LocalDateTime now = LocalDateTime.now();
        //设置打卡时间
        attendanceRecords.setEndTime(now);
        // 将 LocalDateTime 转换为时间戳（单位：毫秒）
        long timestampInMillis = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
//        long timestampInMillis = 1704015600000L;
        //如果为true就表示早退
        if (timestampInMillis < time){
            long reduce = time - timestampInMillis;
            //小时
            double hr = Math.floor(reduce / 3600000 % 24);
            reduce = reduce - (long)(hr * 3600000 );
            // 分钟
            double min = Math.floor(reduce / 60000 % 60);
            String earlyTime = new String();
            earlyTime = hr + "时" + min + "分";
            attendanceRecords.setEarlyTime(earlyTime);
        }
        //执行修改
        updateById(attendanceRecords);
    }

    @Override
    public List<AttendanceRecords> exportData(AttendanceRecords attendanceRecords) {
        LambdaQueryWrapper<AttendanceRecords> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<AttendanceRecords> recordsList = attendanceRecordsMapper.selectList(lambdaQueryWrapper);
        recordsList.forEach( item ->{
            Integer employeeId = item.getEmployeeId();
            Employee employee = employeeService.selectById(employeeId);
            item.setEmployeeName(employee.getName());
            item.setDepartmentName(employee.getDepartmentName());
            //如果迟到的时间非空就返回是
            if (ObjectUtil.isNotEmpty(item.getLateTime())){
                item.setIsLate("是");
            }else {
                item.setIsLate("否");
            }
            if (ObjectUtil.isNotEmpty(item.getEarlyTime())){
                item.setIsEarly("是");
            }else {
                item.setIsEarly("否");
            }
        });
        return recordsList;
    }


}
